package com.example.echoewish.ui.my_activity.login_and_register_activity;

import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.example.echoewish.econstant.Constant;
import com.example.echoewish.pojo.User;
import com.example.echoewish.repository.UserMessageRepository;
import com.example.echoewish.util.LogUtil;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

//与RegisterActivity绑定
public class RegisterViewModel extends ViewModel {
    public MutableLiveData<String> responseMutableLiveData;
    public MutableLiveData<User> newUserMutableLiveData;

    public RegisterViewModel()
    {
        responseMutableLiveData=new MutableLiveData<>();
        newUserMutableLiveData=new MutableLiveData<>();
    }

    public void registerNewUser()
    {
        UserMessageRepository.getInstance().registerNewUsers(newUserMutableLiveData.getValue().account,
                newUserMutableLiveData.getValue().password,new RegisterNewUserCallBack());
    }

    private class RegisterNewUserCallBack implements Callback<ResponseBody>
    {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            try {
                responseMutableLiveData.postValue(response.body().string());
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            new LogUtil().w(LogUtil.CALLBACK_TAG,"注册用户 回调失败"+t);
            responseMutableLiveData.postValue(Constant.HTTPS_GET_CALLBACK_FAIL);
        }
    }
}
